/*
    * Browser.Engine.trident - (boolean) True if the current browser uses the trident engine (e.g. Internet Explorer).
    * Browser.Engine.gecko - (boolean) True if the current browser uses the gecko engine (e.g. Firefox, or any Mozilla Browser).
    * Browser.Engine.webkit - (boolean) True if the current browser uses the webkit engine (e.g. Safari, Google Chrome, Konqueror).
    * Browser.Engine.presto - (boolean) True if the current browser uses the presto engine (e.g. Opera 9).
    * Browser.Engine.name - (string) The name of the engine.
    * Browser.Engine.version - (number) The version of the engine. (e.g. 950)
    * Browser.Plugins.Flash.version - (number) The major version of the flash plugin installed.
    * Browser.Plugins.Flash.build - (number) The build version of the flash plugin installed.
*/


function onlyNumbers(evt)
{
  	var e = evt
	if(window.event){ // IE
		var charCode = e.keyCode;
	} else if (e.which) { // Safari 4, Firefox 3.0.4
		var charCode = e.which
	}
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	return false;
	return true;

}

function homePageButtons()
{
	if($('but1') !== null)
	{
		$('but1').addEvent('click', function(){
			window.location = $('but1').get('rel');
		});
		$('but2').addEvent('click', function(){
			window.location = $('but2').get('rel');
		});
		$('but3').addEvent('click', function(){
			window.location = $('but3').get('rel');
		});
	}
}

//---ACCOUNT DISPLAY PAGE ACTIONS
function initAccounts()
{
	//CMS
	if($('actCMS') !== null)
	{
		$('navProper').innerHTML = $('actCMS').get('rel');
		if($('closeWin') !== null)
		{
			$('closeWin').addEvent('click', function(){
				return false;
			});
		}
		
		if($('modProfile') !== null)
		{
			$('deleteAcct').addEvent('click', function(){
				var c = confirm('Are you sure you want to delete this entry? This cannot be undone.');
				if(c)
				{
					if(opener){opener.location='index.php?page=accounts&type='+this.get('alt')+'&del='+this.get('rel');
					self.close()};
				}
			});
			$('modUpdateDtails').addEvent('click', function(){
				if(this.get('value') == 'Edit Account Details')
				{
					this.set('value', 'Edit Account Profile');
				}
				else
				{
					this.set('value', 'Edit Account Details');
				}
				$('modDetails').fade('toggle');
				$('modProfile').fade('toggle');
			});
			$('modProfile').fade('show');
			$('modDetails').fade('hide');
		}
		if($('addAddress') !== null)
		{
			$('addAddress').addEvent('click', function(){
				$('listGridAdd').innerHTML += '<br /><input type="text" class="existingAdd newver" name="newAdd[]" value=""/>';
				$('priGridAdd').innerHTML += '<br /><input type="text" class="existingAddPri numOnly newverP" name="newAddPri[]" value="" />';
				$('delGridAdd').innerHTML += '<br /><input type="text" class="newEntry twelve" value="NEW" disabled/>';
			});
			$('addDetail').addEvent('click', function(){
				$('delGridMisc').innerHTML += '<br /><input type="text" class="newEntry ten" value="NEW" disabled/>';
				$('typeGridMisc').innerHTML += '<br /><input type="text" class="existingMiscType newverT" name="newMiscType[]" value=""/>';
				$('detailGridMisc').innerHTML += '<br /><input type="text" class="existingMisc newver" name="newMisc[]" value=""/>';
				$('priGridMisc').innerHTML += '<br /><input type="text" class="existingMiscPri numOnly newverP" name="newMiscPri[]" value=""/>';
			});
		}
		if($('editFrm') !== null)
		{
			$('editFrm').addEvent('submit', function(){
				var sub = 'yes';
				var a = $$('.formver');
				for (i=0; i<a.length; i++)
				{
					if(a[i].get('value') <= 0 || a[i].get('value') == '')
					{
						sub = 'no';
					}
				}
				
				var b = $$('.newver');
				var c = $$('.newverP');
				if(b.length > 0)
				{
					for (i=0; i<b.length; i++)
					{
						if(b[i].get('value') != '' )
						{
							if(c[i].get('value') == '0')
							{
								sub = 'no';
							}
						}
					}
				}
				
				if(sub == 'yes')
				{
					var g = confirm('Please note that all \'NEW\' fields that are left blank or incomplete will not be added into the database and all existing entries marked \'DELETED\' will be deleted permanently. Are you sure you want to continue? This cannot be undone.');
					if(g)
					{
						return true;
					}
					else
					{
						return false;
					}
				}
				else
				{
					alert('Some of the fields are not filled in properly [highlighted in red]. Please note that all \'priority\' fields must be filled up with a numeric value greater than 0. Note that incomplete \'NEW\' entries will not be included in the database.');
					for (i=0; i<a.length; i++)
					{
						if(a[i].get('value') == '' || a[i].get('value') == '0')
						{
							a[i].set('style', 'background: #b78585; color: #ffffff');
						}
						else
						{
							a[i].set('style', 'background: #ffffff; color: #333333');
						}
					}
					for (i=0; i<b.length; i++)
					{
						
						if(b[i].get('value') != '')
						{
							if(c[i].get('value') == '' || c[i].get('value') == '0')
							{
								c[i].set('style', 'background: #b78585; color: #ffffff');
							}
						}
					}
					return false;
				}
			});
			
			var a = $$('.numOnly');
			for (i=0; i<a.length; i++)
			{
				a[i].set('onkeypress','return onlyNumbers(event);');
			}
		}
	}
	//---
	if($('accountpage') !== null)
	{
		$$('.altAddList').slide('hide');
		
		$$('.otherBranch').addEvent('click', function(){
			$$('.altAddList').slide('toggle');
			return false;
		});
		
		$$('.globalSelector').addEvent('change', function(){
			window.location = this.get('value');
		});
		
		if($('ClientCButton')!== null)
		{
			$('ClientCButton').addEvent('click', function(){
				window.open('index.php?page=control&sector=accounts&act=new&type=client', 'New Client Account', 'width=475,height=500');
			});
			$('ClientMButton').addEvent('click', function(){
				window.open('index.php?page=control&sector=accounts&act=upd&type=client&entry='+this.get('rel'), 'Modify Client Account', 'width=475,height=500');
			});
		}
		
		if($('SupplierCButton') !== null)
		{
			$('SupplierCButton').addEvent('click', function(){
				window.open('index.php?page=control&sector=accounts&act=new&type=supplier', 'New Client Account', 'width=475,height=500');
			});
			$('SupplierMButton').addEvent('click', function(){
				window.open('index.php?page=control&sector=accounts&act=upd&type=supplier&entry='+this.get('rel'), 'Modify Client Account', 'width=475,height=500');
			});

		}
	}
}

//---NEWITEM.PHP ACTIONS---
function initalizeCPanel()
{
	if($('newItemFormID') !== null)
	{
		$('newItemFormID').addEvent('submit', function(){
			var i = 0;
			var formErrors = new Array;
			if($('itemID').get('value') == '')
			{
				formErrors[i] = "Item Code: No value.\r\n";
				i++;
			}
			else
			{
				var value = $('itemID').get('value');
				if(value.length > 8)
				{
					formErrors[i] = "Item Code: Please limit to 8 Chacaters.\r\n";
					i++;
				}
			}
			if($('itemCat').get('value') == '---')
			{
				formErrors[i] = "Categories: Please select a category.\r\n";
				i++;
			}
			else if($('itemCat').get('value') == 'newCat')
			{
				if($('newCategory').get('value') == '')
				{
					formErrors[i] = "Categories: Please supply a name for new category.\r\n";
					i++;
				}
			}
			
			if($('descArea').get('value') == '')
			{
				formErrors[i] = "Description: Please provide a description.\r\n";
				i++;
			}
			
			if($('notesArea').get('value') == '')
			{
				formErrors[i] = "Notes: Please provide an initial comment.\r\n";
				i++;
			}
			
			if(i == 0)
			{
				var confirmPls = confirm('Are you sure you want to continue submitting this form?'+this.get('rel')+' This cannot be undone.');
				if(confirmPls)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				var errorMsg = "These forms have not been filled up properly:\r\n\r\n";
/* 				alert(formErrors.length); */
				for (k=0; k<formErrors.length; k++)
				{
					errorMsg += formErrors[k];
				}
				alert(errorMsg);
				return false;
			}
		});
	}
	
	if($('itemCat')!== null)
	{
		$('extraSpace').innerHTML = '<input type="hidden" value="1" name="process" />&nbsp;';
		$('sliderCat').slide('hide');
		$('itemCat').addEvent('change', function(){
			if($('itemCat').value == 'newCat')
			{
				showThisSlideThat($('itemCat'), $('sliderCat'), 'backward');
				$('newCategory').set('value','');
			}
		});
		$('bkbtn').addEvent('click', function(){
			showThisSlideThat($('itemCat'), $('sliderCat'), 'forward');
			$('itemCat').set('value', '---');
		});
	}
}
//---random actions
var i = 0;

function showThisSlideThat(showThis, hideThat, direction)
{
	if(direction == 'forward')
	{
		showThis.slide('in');
		hideThat.slide('out');
	}
	else if(direction == 'backward')
	{
		hideThat.slide('in');
		showThis.slide('out');
	}
	else
	{
		//DONOTHING
	}
}
/* -------------------------------------------------------ITEM ADDER FOR CHECKIN-------------------------------*/
/*GRIDS: 2,2,2,2,4*/
function addItem3(container, listener)
{
	var container = $(container);
	$(listener).addEvent('click', function(){
		$('hiderDesc').fade('in');
		var newDiv = new Element('div', {
		    'class': 'itemLine',
		    'id': 'itemD'+i,
		    html: '<div class="grid_4 alpha"><input type="text" name="itemName[]" class="itemInputsLng text" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'" id="itemSrch'+i+'"/></div><div class="grid_2"><input type="text" name="itemSerial[]" class="itemInputs text" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'"/></div><div class="grid_2"><input type="text" name="quantity[]" class="itemInputs number" id="quan'+i+'" ext="unit'+i+'" alt="total'+i+'" rel="itemName'+i+'""/></div><div class="grid_2"><input type="text" id="locSrch'+i+'" name="itemLocation[]" class="itemInputs text" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'"/></div><div class="grid_2 omega"><input type="text" name="itemComment[]" class="itemInputs text" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'"/></div>',
		    styles: {
		       background: '#000'
		    },
		    events: {
		    
		    }	
		});
				
		container.appendChild(newDiv);
		
var toSearch = 'itemSrch'+i;
		var autonew = new Autocompleter.Request.HTML(toSearch, './json/getID.php', {
			    'postVar': 'search',
			    minLength: 3,
			    maxChoices: 10,
			    autoSubmit: false,
			    cache: true,
			    delay: 300,
			    onRequest: function() {
			      $(toSearch).setStyles({
			        'background-image':'url(img/global/indicator.gif)',
			        'background-position':'350px 7px',
			        'background-repeat':'no-repeat'
			      });
			    },
			    onComplete: function() {
			      $(toSearch).setStyle('background','');
			    }
		});

		
		
		var toLoc = 'locSrch'+i;
		var autoview = new Autocompleter.Request.HTML(toLoc, './json/getLoc.php', {
			    'postVar': 'search',
			    minLength: 3,
			    maxChoices: 10,
			    autoSubmit: false,
			    cache: true,
			    delay: 300,
			    onRequest: function() {
			      $(toLoc).setStyles({
			        'background-image':'url(img/global/indicator.gif)',
			        'background-position':'350px 7px',
			        'background-repeat':'no-repeat'
			      });
			    },
			    onComplete: function() {
			      $(toLoc).setStyle('background','');
			    }
		});
		
		
		$$('.selector').addEvent('change', function(){
		});
		
		$$('.number').addEvent('keyup', function(){
			
			$('updater').fade('in');
			
			//document.getElementById('grandTotal').innerHTML = gtotal.toFixed(2);
		});
		i++;
	});
}

/* -------------------------------------------------------ITEM ADDER FOR CHECKOUT-------------------------------*/
function addItem(container, listener)
{
	var container = $(container);
	$(listener).addEvent('click', function(){
		$('hiderDesc').fade('in');
		
		var newDiv = new Element('div', {
		    'class': 'itemLine',
		    'id': 'itemD'+i,
		    html: '<div class="grid_2 alpha"><input type="text" name="itemName[]" class="itemInputs" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'" disabled/></div><div class="grid_2"><select id="selector'+i+'" class="itemInputsSelect"><option value="serial">Serial Number</option><option value="location">Location</option></select></div><div class="grid_2"><input type="text" id="itemSerial'+i+'" name="itemSerial[]" class="itemInputs text" rel="quan'+i+'" ext="unit'+i+'" alt="total'+i+'"/></div><div class="grid_2"><input type="text" name="quantity[]" class="itemInputs number" id="quan'+i+'" ext="unit'+i+'" alt="total'+i+'" rel="itemSerial'+i+'""/></div><div class="grid_2"><input type="text" name="unitPrice[]" value="1.00" class="itemInputs number" id="unit'+i+'" ext="quan'+i+'" alt="total'+i+'" rel="itemSerial'+i+'"/></div><div class="grid_2 omega"><input type="text" name="unitTotal[]" class="itemInputs text greyed" id="total'+i+'" value="0.00" disabled/></div>',
		    styles: {
		       background: '#000'
		    },
		    events: {
		    
		    }

		});		
		container.appendChild(newDiv);
		$$('.text').addEvent('keyup', function(){
			var box = this.get('alt');
			if(this.get('value') == '')
			{
				$(box).set('value', '0.00');
			}
			else
			{
				var rel = parseFloat($(this.get('rel')).get('value'));
				var ext = parseFloat($(this.get('ext')).get('value'));
				
				if(typeOf(rel) == 'number' && typeOf(ext) == 'number')
				{
					
					var total = parseFloat(rel) * parseFloat(ext);
					$(box).set('value', total.toFixed(2));
				}
				else
				{

					$(box).set('value', '0.00');
				}
			}
			
			var gtotal = gtotalStart;
			for (k=0; k<i; k++)
			{
				var ttl = 'total'+k;
				var numval = 0;
				if($(ttl) !== null)
				{
					numval = parseFloat($(ttl).get('value'));
				}
				
				gtotal += numval;
			}
			$('grandTotal').innerHTML = gtotal.toFixed(2);
			if(gtotal != 0 && this.get('value') != '')
			{
				$('updater').fade('in');
			}
		});
		$$('.number').addEvent('keyup', function(){
			
			var other = $(this.get('ext')).get('value');
			var total = parseFloat(other) * parseFloat(this.get('value'));
			var box = $(this.get('alt'));
			
			if(typeOf(total) == 'number')
			{
				if($(this.get('rel')).get('value') == '')
				{
					
					$(box).set('value', '0.00');
				}
				else
				{

					$(box).set('value', total.toFixed(2));
					gtotal = 0;
					var ttl;
					for (k=0; k<i; k++)
					{
						ttl = 'total'+k;
						var numval = 0;
						if($(ttl) !== null)
						{
							numval = parseFloat($(ttl).get('value'));
						}
						gtotal += numval;
					}
					document.getElementById('grandTotal').innerHTML = gtotal.toFixed(2);
					if(gtotal != 0)
					{
						$('updater').fade('in');
					}
				}
			}
			else
			{
				$(box).set('value', '0.00');
				$('updater').fade('out');
			}
			var gtotal = gtotalStart;
			
			//document.getElementById('grandTotal').innerHTML = gtotal.toFixed(2);
		});
		i++;
	});
}

/* ------------------------------------------------------------------END ITEM ADDER CHECKOUT HERE */
// ---- page definers
function initItemPage()
{
	if($('idDelete') !==null)
	{
		$('idDelete').addEvent('submit', function(){
			var confirmPls = confirm('Are you sure you want to continue submitting this form? All items listed in this category, including their attributes will be marked inactive. Permanently. Do you still want to continue? This cannot be undone.');
			if(confirmPls)
			{
				this.set('method', 'POST');
				this.set('action', this.get('rel'));
				return true;
			}
			else
			{
				return false;
			}
		});
	}
	if($('idRename') !== null)
	{
		$('idRename').addEvent('submit', function(){
			var i = 0;
			for (g=0; g<availCategories.length; g++)
			{
				var err = '';
				
				if($('renameTo').get('value') == '')
				{
					err = "Please specify a new category name.";
					i++;
				}
				else if($('renameTo').get('value') == availCategories[g])
				{
					err = "This category name already exists. Please specify a new name.";
					i++;
				}
			}
			if(i > 0)
				{
				alert(err);
				return false;
			}
			else
			{
				var confirmPls = confirm('Are you sure you want to continue submitting this form? This cannot be undone.');
				if(confirmPls)
				{
					this.set('method', 'POST');
					this.set('action', this.get('rel'));
					return true;
				}
				else
				{
					return false;
				}
			}			
		});
	}
	if($('newItemAndCategory') !== null)
	{
		$('extraspace').innerHTML = '&nbsp;<input type="hidden" value="1" name="process" /><input type="hidden" name="category" value="newCat" />';
		$('newItemAndCategory').addEvent('submit', function(){
			
			var formErrors = new Array;
			var i = 0;
			if($('newCategoryName').get('value') == '')
			{
				formErrors[formErrors.length] = "Category: Please supply a Category Name.\r\n";
				i++;
			}
			
			if($('newItemText').get('value') == '')
			{
				formErrors[formErrors.length] = "New Item Code: Please supply an Item Code.\r\n";
				i++;
			}
			else
			{
				var val = $('newItemText').get('value');
				if(val.length > 8)
				{
					formErrors[formErrors.length] = "New Item Code: Please supply an Item Code with 8 Characters or less.\r\n";
					i++;
				}
			}
			if($('newDescArea').get('value') == '')
			{
				formErrors[formErrors.length] = "New Item Description: Please specify a description.\r\n";
				i++;
			}
			if($('newNotesArea').get('value') == '')
			{
				formErrors[formErrors.length] = "New Item Notes: Please specify notes.\r\n";
				i++;
			}
			
			if(i > 0)
			{
				var errorMsg = "Some fields have not been filled up properly:\r\n\r\n";
				for (k=0; k<formErrors.length; k++)
				{
					errorMsg += formErrors[k];					
				}
				alert(errorMsg);
				return false;
			}
			else
			{
				this.set('method', 'POST');
				this.set('action', this.get('rel'));
				var w = window.open('about:blank', 'Administration', 'width=475,height=500');
				this.target = 'Administration';
				var confirmPls = confirm('Are you sure you want to continue submitting this form? This cannot be undone.');
				if(confirmPls)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		});
	}
	if($('locList') !== null)
	{
		$('locList').addEvent('change', function(){
			var thispage = this.get('rel');
			if(this.get('value') == 'new')
			{
				window.location = thispage;
			}
			else
			{
				window.location = thispage+'&location='+this.get('value');
			}
		});
	}
	if($('editItem') !== null)
	{
		$('editItem').addEvent('click', function(){
			window.open(this.get('rel'), 'Administration', 'width=475,height=500');
			return false;
		});
	}
	if($('itemMain') !== null)
	{
		if($('catList') !== null)
		{
			$('catList').slide('hide');
						$('catHide').addEvent('click', function(){
				$('catList').slide('out');
				$('itemList').slide('in');
				return false;
			});
			
			$('catShow').addEvent('click', function(){
				$('itemList').slide('out');
				$('catList').slide('in');
				return false;
			});
			
			$('catLoad').addEvent('click', function(){
				
	/* 			window.location = this.get('rel'); */
				if($('categ').get('value') == '')
				{
					alert('You have not selected a category. Please try again.');
				}
				else
				{
					if($('categ').get('value') == 'all')
					{
						window.location = this.get('rel');
					}
					else
					{
						var main = this.get('rel');
						var categ = $('categ').get('value');
						var loc = main+'&cat='+categ;
						
						window.location = loc;
					}
				}
				return false;
			});
			
			$('item').addEvent('change', function(){
				var itemID = this.get('value');
				var itemRoot = $('catLoad').get('rel');
				var category = $('itemList').get('rel');
				
				if(category == 'all' || category === null)
				{
					category2 = '';
				}
				else
				{
					category2 = '&cat='+category;
				}
				
				window.location = itemRoot+category2+'&id='+itemID;
			});
		}
		else
		{
			$('categList').addEvent('change', function(){
				var itemRoot = $('itemMain').get('rel');
				var connect = '&cat=';
				var link = this.get('value');
				window.location = itemRoot+connect+link;
			});

		}		
	}
}


function initOrderPage()
{
	if($('orderPointer') !== null)
	{
		
		if($('orderPointer').get('rel') == 'Check-In')
		{
			var startTotal = gtotalStart;
			$('grandTotal').innerHTML = startTotal.toFixed(2);
			if($('existing') === null)
			{
				$$('.fader').fade('hide');
				$('hiderDesc').fade('hide');
				$('updater').fade('hide');
			}
			new Picker.Date($$('.inputDate'), {
				timePicker: true,
				positionOffset: {x: 5, y: 0},
				pickerClass: 'datepicker_dashboard',
				useFadeInOut: !Browser.ie
			});
			addItem3('itemConstructor', 'itemAdder');
			$('itemCodeHelp').addEvent('click', function(){
				alert('This field has an autocomplete form. Type in the item code and search results should come out below this field. If you wish to search by item categories, type in "category:" follwed by a space then your search term. Example: category: Cup');
				return false;
			});
			//itemConstructor - > div cointaining items to be built.
			//itemAdder - > event listener.
		}
		else
		{
			var startTotal = gtotalStart;
			$('grandTotal').innerHTML = startTotal.toFixed(2);
			if($('existing') === null)
			{
				$$('.fader').fade('hide');
				$('hiderDesc').fade('hide');
				$('updater').fade('hide');
			}
			new Picker.Date($$('.inputDate'), {
				timePicker: true,
				positionOffset: {x: 5, y: 0},
				pickerClass: 'datepicker_dashboard',
				useFadeInOut: !Browser.ie
			});
			addItem('itemConstructor', 'itemAdder');
			//itemConstructor - > div cointaining items to be built.
			//itemAdder - > event listener.
		}
	}
}

function initialize()
{
	var links = $$('a');
	for (i=0; i<links.length; i++)
	{
		if(links[i].get('rel') == 'popup')
		{
			links[i].addEvent('click', function(){
				window.open(this.get('href'), 'Administration', 'width=475,height=500');
				return false;
			});
		}
	}
	window.addEvent('load',function() {
		
	});
}

window.addEvent('domready',function(){
	homePageButtons();
	initalizeCPanel();
	initItemPage();
	initOrderPage();
	initialize();
	initAccounts();
	
	$$('.linkButton').addEvent('click', function(){
		window.location = this.get('alt');
	});
});